<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Class</title>
</head>
<body>
    <h1>Class</h1>

    <script>
        // 总是使用class，避免直接操作prototype
        // bad
        function Queue(contents = []) {
            this.queue = [...contents];
        }
        Queue.prototype.pop = function() {
            return this.queue.pop();
        };

        // good
        class Queue {
            constructor(contents = []) {
                this.queue = [...contents];
            }
            
            pop() {
                return this.queue.pop();
            }
        }

        // 使用extends进行继承
        // bad
        const inherits = require('inherits');
        function PeekableQueue(contents) {
            Queue.apply(this, contents);
        }
        inherits(PeekableQueue, Queue);
        PeekableQueue.prototype.peek = function() {
            return this.queue[0];
        };

        // good
        class PeekableQueue extends Queue {
            peek() {
                return this.queue[0];
            }
        }

        // 实际应用示例
        class Component {
            constructor(props = {}) {
                this.props = props;
                this.state = {};
                this.init();
            }

            init() {
                this.render();
                this.bindEvents();
            }

            setState(newState) {
                this.state = { ...this.state, ...newState };
                this.render();
            }

            render() {
                throw new Error('子类必须实现render方法');
            }

            bindEvents() {}
        }

        class Button extends Component {
            constructor(props) {
                super(props);
                this.state = {
                    clicked: false
                };
            }

            render() {
                return `
                    <button class="${this.state.clicked ? 'active' : ''}">
                        ${this.props.text || 'Button'}
                    </button>
                `;
            }

            bindEvents() {
                this.element.addEventListener('click', () => {
                    this.setState({ clicked: true });
                });
            }
        }
    </script>
</body>
</html> 